﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AGR.Services.FormInformation;
using AGR.Model;
using AGR.Services;

namespace AGR.Web.Pages.Administration
{
    public partial class FormInformation : System.Web.UI.Page
    {
        private IFormInformationService _formInformationService = new FormInformationService();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.ClearMessage();
                this.LoadGrid();
            }
        }

        #region Button Methods

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            CountryGridView.ShowFooter = true;
            CountryGridView.EditIndex = -1;
            this.LoadGrid();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            bool selected = false;
            int selectCount = 0;
            int deleteCount = 0;
            string succesMessages = string.Empty;
            string errorMessages = string.Empty;

            IList<ActionResult> results = new List<ActionResult>();

            for (int i = 0; i < CountryGridView.Rows.Count; i++)
            {
                var row = CountryGridView.Rows[i];
                bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;

                if (isChecked)
                {
                    string primaryKey = (string)this.CountryGridView.DataKeys[i].Value;
                    results.Add(_formInformationService.DeleteCountry(primaryKey, "TestUser"));
                    selected = true;
                    selectCount++;
                }
            }

            if (selected == false)
            {
                this.ShowMessage("No record(s) were selected for deletion.", SiteMaster.MessageType.Information);
                return;
            }

            foreach (ActionResult result in results)
            {
                if (result.Success)
                {
                    succesMessages = result.Message;
                    deleteCount++;
                }
                else
                    errorMessages = result.Message;
            }

            if (!string.IsNullOrEmpty(succesMessages))
                this.ShowMessage(succesMessages, SiteMaster.MessageType.Success);

            if (!string.IsNullOrEmpty(errorMessages))
                this.ShowMessage(errorMessages + " " + (selectCount - deleteCount) + " record(s) was not deleted.", SiteMaster.MessageType.Error);

            CountryGridView.EditIndex = -1;
            this.LoadGrid();
        }

        #endregion

        #region GridView Methods

        protected void CountryGridView_OnRowCommand(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Insert")
            {
                string primaryKey = ((TextBox)CountryGridView.FooterRow.FindControl("txtCountryName")).Text.ToString();

                var exists = _formInformationService.GetCountries().Where(x => x.CountryName.Equals(primaryKey));

                if (exists.Count() > 0)
                {
                    this.ShowMessage("Your action could not be completed. A record with country (" + primaryKey + ") already exists on the system.", SiteMaster.MessageType.Warning);
                    return;
                }

                var entity = new Country
                {
                    CountryCode = ((TextBox)CountryGridView.FooterRow.FindControl("txtCountryCode")).Text.ToString(),
                    CountryName = primaryKey,
                    CountryLong = ((TextBox)CountryGridView.FooterRow.FindControl("txtCountryLong")).Text.ToString(),
                    Nationality = ((TextBox)CountryGridView.FooterRow.FindControl("txtNationality")).Text.ToString(),
                    Displayed = ((CheckBox)CountryGridView.FooterRow.FindControl("chkDisplayed")).Checked,
                    UserCreated = "TestUser"
                };

                var result = _formInformationService.AddCountry(entity);

                if (result.Success)
                {
                    this.ShowMessage(result.Message, SiteMaster.MessageType.Success);
                    CountryGridView.ShowFooter = false;
                    CountryGridView.EditIndex = -1;
                    this.LoadGrid();
                }
                else
                    this.ShowMessage(result.Message, SiteMaster.MessageType.Error);
            }
            else if (e.CommandName == "CancelInsert")
            {
                this.ClearMessage();
                CountryGridView.ShowFooter = false;
                CountryGridView.EditIndex = -1;
                this.LoadGrid();
            }
        }

        protected void CountryGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string primaryKey = ((TextBox)CountryGridView.Rows[e.RowIndex].FindControl("txtCountryName")).Text.ToString();

            var entity = _formInformationService.GetCountry(x => x.CountryName.Equals(primaryKey));

            entity.CountryCode = ((TextBox)CountryGridView.Rows[e.RowIndex].FindControl("txtCountryCode")).Text.ToString();
            entity.CountryName = primaryKey;
            entity.CountryLong = ((TextBox)CountryGridView.Rows[e.RowIndex].FindControl("txtCountryLong")).Text.ToString();
            entity.Nationality = ((TextBox)CountryGridView.Rows[e.RowIndex].FindControl("txtNationality")).Text.ToString();
            entity.Displayed = ((CheckBox)CountryGridView.Rows[e.RowIndex].FindControl("chkDisplayed")).Checked;
            entity.UserModified = "TestUser";

            var result = _formInformationService.UpdateCountry(entity);

            if (result.Success)
            {
                this.ShowMessage(result.Message, SiteMaster.MessageType.Success);
                CountryGridView.EditIndex = -1;
                this.LoadGrid();
            }
            else
                this.ShowMessage(result.Message, SiteMaster.MessageType.Error);
        }

        protected void CountryGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.ClearMessage();
            CountryGridView.ShowFooter = false;
            CountryGridView.EditIndex = e.NewEditIndex;
            this.LoadGrid();
        }

        protected void CountryGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            CountryGridView.EditIndex = -1;
            this.LoadGrid();
        }

        protected void CountryGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            CountryGridView.PageIndex = e.NewPageIndex;
            CountryGridView.EditIndex = -1;
            this.LoadGrid();
        }

        #endregion

        #region Private Methods

        private void LoadGrid()
        {
            var countries = _formInformationService.GetCountries();

            if (countries.Count == 0)
            {
                countries.Add(new Country());
                CountryGridView.ShowFooter = true;
                CountryGridView.EditIndex = -1;

                CountryGridView.DataSource = countries;
                CountryGridView.DataBind();
                CountryGridView.Rows[0].Visible = false;
            }
            else
            {
                CountryGridView.DataSource = countries;
                CountryGridView.DataBind();
            }
        }

        private void ShowMessage(string message, AGR.Web.SiteMaster.MessageType messagetype)
        {
            var master = (SiteMaster)Page.Master;
            master.ShowMessage(message, messagetype);
        }

        private void ClearMessage()
        {
            var master = (SiteMaster)Page.Master;
            master.ClearMessage();
        }

        #endregion
    }
}